<template>
	<view id="moments">
	<!-- 获取当前用户的头像和昵称 背景图在css样式中，以base64格式保存-->
	<unicloud-db v-slot:default="{data, loading, error, options}" collection="uni-id-users"
	field="_id,nickname,avatar_file"  where="_id== $cloudEnv_uid"  >
		<view v-if="error">{{error.message}}</view>
		<view v-else class="home-pic">
			<view class="home-pic-base">
				<view class="top-pic">
					<image class="header" v-if="!!data[0].avatar_file" :src="data[0].avatar_file.url" @tap="test"></image>
				</view>
				<view class="top-name">{{data[0].nickname}}</view>
			</view>
		</view>
	</unicloud-db>
	<!-- 日常询问列表主体-->
		<view class="moments__post" v-for="(post,index) in posts" :key="index" :id="'post-'+index">
		
			<view class="post-left">
				<image class="post_header" :src="post.avatar"></image>
			</view>

			<view class="post_right">
				<text class="post-username">{{post.nikename}}</text>
				<view id="paragraph" class="paragraph">{{post.content}}</view>
				<view id="contact" v-if="!!post.contacts" class="contact">联系方式：{{post.contacts}}</view>
				<!-- 相册 -->
				<view v-if="post.imgs.length > 0" class="thumbnails">
					<view :class="post.imgs.length === 1?'my-gallery':'thumbnail'" v-for="(image, index_images) in post.imgs" :key="index_images">
						<image class="gallery_img" lazy-load mode="aspectFill" :src="image.url" :data-src="image.url" @tap="previewImage(post.imgs,index_images)"></image>
					</view>
				</view>
				<!-- 资料条 -->
				<view class="toolbar">
					<uni-dateformat :date="post.last_modify_date - 7200000"></uni-dateformat>
					<view class="like" @tap="clickLove(post)">
						<image :src="post.has_like===false?'https://mp-ba6dadac-aa5f-4abc-a3b4-3abcf3c08fc3.cdn.bspapp.com/cloudstorage/7e1e19a0-1976-4e99-869c-5582577f00df.png'
						:'https://mp-ba6dadac-aa5f-4abc-a3b4-3abcf3c08fc3.cdn.bspapp.com/cloudstorage/c038a963-028f-40a8-b5a6-030181afb59e.png'"></image>
					</view>
					<view class="comment" @tap="toComment(post._id)">
						<image src="https://mp-ba6dadac-aa5f-4abc-a3b4-3abcf3c08fc3.cdn.bspapp.com/cloudstorage/b7d2748f-457a-43bf-8fd3-713b356e5eb2.png"></image>
					</view>
				</view>
				<!-- 赞／评论区 -->
				<view class="post-footer">
					<view class="footer_content"> <!-- liked.jpg-->
						<image class="liked" src="https://mp-ba6dadac-aa5f-4abc-a3b4-3abcf3c08fc3.cdn.bspapp.com/cloudstorage/eb2bee3f-d7c8-42b7-b6ba-357ca90c0b54.png"></image>
						<!-- 以当前帖子ID去likepost表中查找对应的昵称-->
						<text class="nickname"  v-for="(user,index_like) in post.postLikeList" :key="index_like">{{user.user_nickname}}</text>
					</view>
					<view class="footer_content" v-for="(comment,comment_index) in post.postComment" :key="comment_index" @tap="reply(index,comment_index)">
						<text class="comment-nickname">{{comment.user_nickname}}: <text class="comment-content">{{comment.comment_content}}</text></text>
					</view>
				</view> 
			</view>
			<!-- 结束 post -->
		</view>

		<view class="foot" v-if="showInput">
			<chat-input @send-message="send_comment" @blur="blur" :focus="focus" :placeholder="input_placeholder"></chat-input>
			<!-- <chat-input @send-message="send_comment" @blur="blur" :placeholder="input_placeholder"></chat-input> -->
		</view>
		<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>
	</view>

</template>

<script>
	// 状态存储的信息
	import feedMixin from '@/mixins/todoFeed.js'
	export default {
		mixins: [feedMixin],
		data() {
			return {
				posts: [],//帖子内容
				user_id: 4,
				index: '',
				comment_index: '',	
				loadMoreText: "加载中...",
				showLoadMore: false,
			}
		},
		mounted() {
			uni.getStorage({
				key: 'posts',
				success: function (res) {
					console.log(res.data);
					this.posts = res.data;
				}
			});
		},
		onLoad() {
			//初始化日常询问信息
			this.getInquiry()
			uni.getSystemInfo({ //获取设备信息
				success: (res) => {
					this.screenHeight = res.screenHeight;
					this.platform = res.platform;
				}
			});
			uni.startPullDownRefresh();
		},
		onShow() {
			uni.onWindowResize((res) => { //监听窗口尺寸变化,窗口尺寸不包括底部导航栏
				if(this.platform === 'ios'){
					this.windowHeight = res.size.windowHeight;
					this.adjust();
				}else{
					if (this.screenHeight - res.size.windowHeight > 60 && this.windowHeight <= res.size.windowHeight) {
						this.windowHeight = res.size.windowHeight;
						this.adjust();
					}
				}
			});
		},
		onHide() {
			uni.offWindowResize(); //取消监听窗口尺寸变化
		},
		onUnload() {
			this.max = 0,
			this.data = [],
			this.loadMoreText = "加载更多",
			this.showLoadMore = false;
		},		
		onPullDownRefresh() { //监听下拉刷新动作
			console.log('onPullDownRefresh');
			// 这里获取数据
			//初始化数据
			this.posts = []
			this.getInquiry()
			setTimeout(function() {
				uni.stopPullDownRefresh(); //停止下拉刷新
			}, 1000);
		},
		onNavigationBarButtonTap(e) {//监听标题栏点击事件
			if (e.index == 0) {
				this.navigateTo('../publish/publish')
			}
		},
		computed:{
			
		},
		methods: {
			//初始化日常询问信息
			async getInquiry(){
				const dbLike = uniCloud.databaseForJQL()
				const dbComment = uniCloud.databaseForJQL()
				const db = uniCloud.databaseForJQL()
				const temp1 = db.collection("NeuHelper-Posts").where("category_id == '642d7f6ce766bb2975cd4df7'")
				.field('_id,user_id,category_id,title,like_count,imgs,content,last_modify_date,contacts').getTemp() 
				const temp2 = db.collection('uni-id-users').field('_id,nickname,avatar_file').getTemp()
				let dataPost = await db.collection(temp1,temp2).get()
				dataPost = dataPost.data 
			//	console.log("推荐数据：")
			//	console.log(dataPost)
				// 喜欢的帖子
				const db2 =  uniCloud.databaseForJQL()
				let LikeList  = await  db2.collection("NeuHelper-LikePosts").where("user_id== $cloudEnv_uid ")
				.field('post_id').get()
				LikeList = LikeList.data
			//	console.log(LikeList)		
				var mp = new Map()
				for(var i = 0 ; i < LikeList.length ; ++i)mp.set(LikeList[i].post_id,true)
				for(var i=0; i < dataPost.length ; ++i){
					let likeBool = mp.has(dataPost[i]._id) // 判读当前帖子用户自己是否点赞过？
					try{
						  await dbLike.collection("NeuHelper-LikePosts").where("post_id=='" + dataPost[i]._id  + "'").field("user_nickname").get()
					 } catch (e) {
					uni.showModal({
						title: '提示',
						content: e.message
					})
				}
				let postLikeList = await dbLike.collection("NeuHelper-LikePosts").where("post_id=='" + dataPost[i]._id  + "'").field("user_nickname").get()
					 postLikeList = postLikeList.data
					
					 let postComment = await dbComment.collection("NeuHelper-PostComments").where("post_id=='" + dataPost[i]._id  + "'")
					 .field("user_nickname,comment_content").get()
					 postComment = postComment.data 
					
					this.posts.push({
						_id:dataPost[i]._id, // ID
						title:dataPost[i].title, 
						content:dataPost[i].content,
						contacts:dataPost[i].contacts,
						imgs:[],
						avatar:dataPost[i].user_id[0].avatar_file.url,
						nickname:dataPost[i].user_id[0].nickname,
						like_count:dataPost[i].like_count,
						has_like:likeBool,
						post_user_id:dataPost[i].user_id[0]._id, // 发布帖子的用户ID
						last_modify_date:dataPost[i].last_modify_date,
						postLikeList:postLikeList  ,// 当前帖子点赞的人的昵称 
						postComment:postComment  // 当前帖子对应的评论
					})
					if(dataPost[i].imgs.length > 0) this.posts[i].imgs = dataPost[i].imgs;
				}
			},
			test(){
				this.navigateTo('../test/test');
			},
			navigateTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			toComment(post_id) {
				this.navigateTo('/subpages/InquiryInfo/InquiryInfo?id=' + post_id);
			},
			//图片预览
			previewImage(imageList,image_index) {
				// 传递过来的 imageList 是一个有图片url的对象，需要先提取
				let imgs = []
				for(var i = 0 ; i < imageList.length; ++i )imgs.push(imageList[i].url)
				var current = imgs[image_index];
				uni.previewImage({
				current:current,
				urls: imgs,
				fail: function(err) {
				console.log(err.errMsg);
				}
				});
			},
			goPublish() {
				uni.navigateTo({
					url: './publish/publish',
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			}
		}
	}
</script>

<style scoped>
	@import url("index.css");
</style>
